import sys
import os
import subprocess
from defines import *


def main(isa_name):
    isa_rom_path = os.path.join(MAIN_PATH, r'sim\isa_rom')
    file_list = os.listdir(isa_rom_path)
    source_file = None
    for file in file_list:
        name = file.split('.')[0]
        isa_name_temp = name.split('-')[-1]
        if isa_name_temp == isa_name:
            source_file = file
            break

    if source_file is None:
        print('!!! ERROR !!!')
        print('------------- don\'t find valid ISA sim file!')
    else:
        source_file_path = os.path.join(isa_rom_path, source_file)
        source_FH = open(source_file_path, 'r')
        buf = source_FH.read()
        source_FH.close()

        target_FH = open(DATA_FILE, 'w')
        target_FH.write(buf)
        target_FH.close()

        vvp_cmd = ['vvp']
        vvp_cmd.append(OUT_FILE_PATH)
        process = subprocess.Popen(vvp_cmd)
        try:
            process.wait(timeout=10)
        except:
            print('Error: vpp timeout!')


if __name__ == '__main__':
    sys.exit(main(sys.argv[1]))